﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.SessionState;
using System.IO;
using AcctrueWMS.Foundation.DAL;

namespace AcctrueWMS.Foundation.Web
{
    /// <summary>
    /// 上传文件处理程序
    /// </summary>
    public class UploadHandler : IHttpHandler, IRequiresSessionState
    {

        #region IHttpHandler 成员

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //文件上传存储路径
            string uploadPath = context.Server.MapPath(context.Request.ApplicationPath + System.Configuration.ConfigurationManager.AppSettings["uploadFilePath"].ToString());
            string guid = context.Request.QueryString["guid"];
            if (string.IsNullOrEmpty(guid)) return;

            for (int i = 0; i < context.Request.Files.Count; i++)
            {
                HttpPostedFile uploadFile = context.Request.Files[i];
                if (uploadFile.ContentLength > 0)
                {
                    try
                    {
                        string extName = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf('.'));
                        string filePath = guid + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + DateTime.Now.Millisecond;
                        //新增记录
                        string sSql = "INSERT INTO sys_attachments(fileID, filePath, [fileName], extName) VALUES(@fileID,@filePath,@fileName,@extName)";
                        int iRet = WMSqlExcuter.ExecuteNonQuery(sSql, CommandType.Text,
                            DBFactory.NewParameter("fileID", guid),
                            DBFactory.NewParameter("filePath", filePath),
                            DBFactory.NewParameter("fileName", uploadFile.FileName),
                            DBFactory.NewParameter("extName", extName)
                            );
                        //保存文件
                        uploadFile.SaveAs(Path.Combine(uploadPath, filePath + extName));
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                    }
                }
            }

            HttpContext.Current.Response.Write(" ");
        }

        #endregion
    }
}
